<template>
  <div class="sw-month-picker">
    <RangePicker
      ref="monthPickerRef"
      :open="openMonthPicker"
      class="sw-range-picker"
      :mode="['month', 'month']"
      v-model:value="currentValue"
      valueFormat="YYYY-MM"
      format="YYYY-MM"
      @panelChange="onPanelChange"
      dropdownClassName="sw-month-picker"
      :getCalendarContainer="getElement"
      @openChange="openChange"
      @change="changeTime"
    >
      <template #renderExtraFooter>
        <div style="width: 100%; text-align: right;">
          <a-button type="primary" size="small" @click="changeTime">确定</a-button>
        </div>
      </template>
    </RangePicker>
  </div>
</template>
<script lang="ts" setup>
  import { ref, onMounted, watch } from 'vue';
  import { DatePicker } from 'ant-design-vue';
  import moment from 'moment';

  const RangePicker = DatePicker.RangePicker
  const props = defineProps<{
    value: moment.Moment[]
  }>()
  const emits = defineEmits(['update:value', 'ok'])

  const getElement = ref<Fn<HTMLElement> | undefined>(undefined)
  const currentValue = ref<moment.Moment[]>(props.value)

  const openMonthPicker = ref<boolean>(false)
  const monthPickerRef = ref<InstanceType<typeof DatePicker> | null>(null)

  const onPanelChange = (val: moment.Moment[]) => {
    currentValue.value = val
  }
  
  const openChange = (open: boolean) => {
    openMonthPicker.value = open
    if (open) {
      currentValue.value = props.value
    }
  }

  const changeTime = () => {
    openMonthPicker.value = false
    emits('update:value', currentValue.value)
    emits('ok')
  }

  watch(() => props.value, (n) => {
    currentValue.value = n
  }, {
    immediate: true
  })

  onMounted(() => {
    getElement.value = () => document.querySelector(`.sw-month-picker`) as HTMLElement
  })
</script>

<style lang="less" scoped>
  .sw-month-picker {
    ::v-deep(.ant-calendar-range-bottom) {
      display: flex;
      justify-content: flex-end;
    }
  }
</style>
